package top.codef.secure.config.delegates;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.context.SecurityContextHolderFilter;

import com.fasterxml.jackson.databind.ObjectMapper;

import top.codef.secure.config.interfaces.CerberusHttpSecurityConfig;
import top.codef.secure.filters.CaptchaFilter;
import top.codef.secure.interfaces.CaptchaRepository;
import top.codef.secure.properties.CerberusCaptchaProperties;

@Configuration
@EnableConfigurationProperties(CerberusCaptchaProperties.class)
@ConditionalOnBean(CaptchaRepository.class)
@ConditionalOnProperty(name = "cerberus.secure.captcha.enabled", havingValue = "true")
@Order(2)
public class CerberusCaptchaConfig implements CerberusHttpSecurityConfig {

	@Autowired
	private ObjectMapper objectMapper;

	@Autowired
	private CerberusCaptchaProperties cerberusCaptchaProperties;

	@Autowired
	private CaptchaRepository captchaRepository;

	private final Log logger = LogFactory.getLog(CerberusCaptchaConfig.class);

	@Override
	public void secure(HttpSecurity httpSecurity) throws Exception {
		logger.debug("开始配置人机验证");
		CaptchaFilter captchaFilter = new CaptchaFilter(captchaRepository, objectMapper,
				cerberusCaptchaProperties.getCaptchaUris());
		httpSecurity.addFilterAfter(captchaFilter, SecurityContextHolderFilter.class);
	}

}
